#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Trace Cleanup Verification Module
痕迹清理闭环验证模块

该模块实现：
1. 痕迹清理效果验证
2. 模拟蓝队检测流程
3. 残留痕迹自动检测
4. 二次清理触发机制
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

import os
import re
import sys
import time
import glob
import json
import hashlib
import subprocess
import platform
from collections import defaultdict

# 导入安全工具
try:
    from core.security_utils import SecureCommandExecutor, SecurityValidator
    SECURITY_UTILS_AVAILABLE = True
except ImportError:
    SECURITY_UTILS_AVAILABLE = False
    print("[!] 安全工具模块不可用，将使用基本安全检查")

# Python 2/3 兼容性
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    import ConfigParser as configparser
else:
    string_types = str
    text_type = str
    import configparser


class TraceVerifier(object):
    """痕迹验证器"""
    
    def __init__(self):
        self.verification_rules = self._load_verification_rules()
        self.blue_team_checks = self._load_blue_team_checks()
        self.found_traces = []
        self.verification_report = {}
    
    def _get_network_commands(self):
        """获取跨平台网络命令"""
        if platform.system() == 'Windows':
            return [
                'netstat -an',
                'powershell "Get-NetTCPConnection | Format-Table -AutoSize"'
            ]
        else:
            return [
                'netstat -tulpn',
                'ss -tulpn',
                'lsof -i',
                'iptables -L -n'
            ]
    
    def _get_platform_commands(self, command_type):
        """获取平台特定的命令"""
        system = platform.system().lower()
        
        commands = {
            'forensic_commands': {
                'windows': [
                    # 日志分析
                    'powershell "Get-EventLog -LogName Security -Newest 100 | Where-Object {$_.Message -like \'*privilege*\'}"',
                    'powershell "Get-EventLog -LogName System -Newest 100 | Where-Object {$_.Message -like \'*exploit*\'}"',
                    'powershell "Get-WinEvent -FilterHashtable @{LogName=\'Security\'; ID=4624,4625} -MaxEvents 50"',
                    
                    # 进程分析
                    'powershell "Get-Process | Where-Object {$_.ProcessName -like \'*exploit*\' -or $_.ProcessName -like \'*payload*\'} | Format-Table -AutoSize"',
                    'powershell "Get-Process | Select-Object ProcessName,Id,CPU,WorkingSet | Format-Table -AutoSize"',
                    'powershell "Get-CimInstance -ClassName Win32_Process | Select-Object ProcessId,Name,CommandLine | Format-Table -AutoSize"',
                    
                    # 文件系统分析
                    'powershell "Get-ChildItem -Path C:\\Temp -Recurse -Force | Where-Object {$_.Name -like \'*exploit*\' -or $_.Name -like \'*payload*\'}"',
                    'powershell "Get-ChildItem -Path $env:TEMP -Recurse -Force | Where-Object {$_.Name -like \'*suspicious*\'}"',
                    'powershell "Get-ChildItem -Path C:\\ -Hidden -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.FullName -like \'*temp*\'}"',
                    
                    # 网络分析
                    'netstat -an | findstr ":4444 :5555 :6666 :8080"',
                    'powershell "Get-NetTCPConnection | Where-Object {$_.State -eq \'Listen\'} | Format-Table -AutoSize"',
                    'powershell "Get-NetTCPConnection | Where-Object {$_.State -eq \'Established\'} | Format-Table -AutoSize"',
                    
                    # 系统配置分析
                    'powershell "Get-LocalUser | Format-Table -AutoSize"',
                    'powershell "Get-LocalGroupMember -Group Administrators"',
                    'schtasks /query /fo list',
                    'powershell "Get-Service | Where-Object {$_.Status -eq \'Stopped\'} | Format-Table -AutoSize"',
                    
                    # 注册表分析
                    'powershell "Get-ItemProperty -Path \'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\'"',
                    'powershell "Get-ItemProperty -Path \'HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\'"'
                ],
                'linux': [
                    # 日志分析
                    'grep -r "sudo" /var/log/',
                    'grep -r "su " /var/log/',
                    'grep -r "privilege" /var/log/',
                    'grep -r "exploit" /var/log/',
                    
                    # 进程分析
                    'ps aux | grep -E "(exploit|payload|shell|backdoor)"',
                    'pstree -p',
                    'lsof +L1',  # 检查已删除但仍在使用的文件
                    
                    # 文件系统分析
                    'find /tmp -type f -name "*exploit*" -o -name "*payload*"',
                    'find /var/tmp -type f -name "*suspicious*"',
                    'find /dev/shm -type f',
                    'find / -type f -name ".*" -path "/tmp/*" -o -path "/var/tmp/*"',
                    
                    # 网络分析
                    'netstat -tulpn | grep -E ":(4444|5555|6666|8080)"',
                    'ss -tulpn | grep LISTEN',
                    'lsof -i | grep ESTABLISHED',
                    
                    # 系统配置分析
                    'cat /etc/passwd | grep -E "shell|bash"',
                    'cat /etc/sudoers',
                    'crontab -l',
                    'systemctl list-units --failed',
                    
                    # 内核模块分析
                    'lsmod | grep -v "^Module"',
                    'dmesg | grep -E "(exploit|malware|suspicious)"',
                    
                    # 审计日志分析
                    'ausearch -k user_cmd',
                    'ausearch -k privileged',
                    'ausearch -m USER_CMD',
                    'ausearch -m SYSCALL'
                ]
            },
            'memory_analysis': {
                'windows': [
                    # 内存分析
                    'powershell "Get-Process | Select-Object ProcessName,WorkingSet,VirtualMemorySize | Sort-Object WorkingSet -Descending | Select-Object -First 20"',
                    'powershell "Get-CimInstance -ClassName Win32_Process | Select-Object ProcessId,PageFileUsage,WorkingSetSize"',
                    'powershell "Get-Counter \'\\Memory\\Available MBytes\'"',
                    
                    # 句柄分析
                    'powershell "Get-Process | Select-Object ProcessName,Handles | Sort-Object Handles -Descending | Select-Object -First 10"'
                ],
                'linux': [
                    # 内存转储分析
                    'cat /proc/*/maps | grep -E "(rwx|--x)"',
                    'cat /proc/*/smaps | grep -A1 "Pss:"',
                    'pmap -x $(pgrep -f suspicious)',
                    
                    # 共享内存分析
                    'ipcs -m',
                    'ipcs -s',
                    'ipcs -q'
                ]
            },
            'timeline_analysis': {
                'windows': [
                    # 时间线分析
                    'powershell "Get-ChildItem -Path C:\\Temp -Recurse | Where-Object {$_.LastWriteTime -gt (Get-Date).AddHours(-1)}"',
                    'powershell "Get-ChildItem -Path $env:TEMP -Recurse | Where-Object {$_.LastWriteTime -gt (Get-Date).AddHours(-1)}"',
                    'powershell "Get-EventLog -LogName Security -After (Get-Date).AddHours(-1) | Select-Object -First 50"',
                    'powershell "Get-WinEvent -FilterHashtable @{LogName=\'System\'; StartTime=(Get-Date).AddHours(-1)} | Select-Object -First 50"'
                ],
                'linux': [
                    # 时间线分析
                    'find /tmp -type f -newermt "1 hour ago"',
                    'find /var/tmp -type f -newermt "1 hour ago"',
                    'find /dev/shm -type f -newermt "1 hour ago"',
                    'last -n 50',
                    'lastlog'
                ]
            }
        }
        
        if command_type in commands:
            return commands[command_type].get(system, commands[command_type].get('linux', []))
        
        return []
    
    def _load_verification_rules(self):
        """加载验证规则"""
        if platform.system() == 'Windows':
            return {
                'log_files': {
                    'paths': [
                        'C:\\Windows\\System32\\winevt\\Logs\\Security.evtx',
                        'C:\\Windows\\System32\\winevt\\Logs\\System.evtx',
                        'C:\\Windows\\System32\\winevt\\Logs\\Application.evtx'
                    ],
                    'patterns': [
                        r'privilege.*',
                        r'escalation.*',
                        r'exploit.*',
                        r'malware.*',
                        r'suspicious.*'
                    ]
                },
                'process_traces': {
                    'paths': [
                        'C:\\Windows\\Temp\\*',
                        'C:\\Temp\\*',
                        '%TEMP%\\*'
                    ],
                    'patterns': [
                        r'.*exploit.*',
                        r'.*payload.*',
                        r'.*shell.*',
                        r'.*backdoor.*'
                    ]
                },
                'network_traces': {
                    'commands': self._get_network_commands(),
                    'patterns': [
                        r'.*:4444.*',
                        r'.*:5555.*',
                        r'.*:6666.*',
                        r'.*:8080.*'
                    ]
                },
                'system_traces': {
                    'commands': [
                        'schtasks /query',
                        'powershell "Get-Service"',
                        'powershell "Get-Process"'
                    ],
                    'patterns': [
                        r'.*exploit.*',
                        r'.*backdoor.*',
                        r'.*malware.*'
                    ]
                }
            }
        else:
            return {
                'log_files': {
                    'paths': [
                        '/var/log/auth.log',
                        '/var/log/secure',
                        '/var/log/messages',
                        '/var/log/syslog',
                        '/var/log/audit/audit.log',
                        '/var/log/kern.log',
                        '/var/log/daemon.log'
                    ],
                    'patterns': [
                        r'sudo.*',
                        r'su\s+.*',
                        r'ssh.*',
                        r'login.*',
                        r'privilege.*',
                        r'escalation.*',
                        r'exploit.*',
                        r'malware.*',
                        r'suspicious.*'
                    ]
                },
                'process_traces': {
                    'paths': [
                        '/proc/*/cmdline',
                        '/proc/*/comm',
                        '/proc/*/environ',
                        '/proc/*/status'
                    ],
                    'patterns': [
                        r'.*exploit.*',
                        r'.*payload.*',
                        r'.*shell.*',
                        r'.*backdoor.*',
                        r'.*malware.*'
                    ]
                },
                'file_traces': {
                    'paths': [
                        '/tmp/*',
                        '/var/tmp/*',
                        '/dev/shm/*',
                        '/home/*/.ssh/*',
                        '/root/.ssh/*'
                    ],
                    'patterns': [
                        r'.*\.sh$',
                        r'.*exploit.*',
                        r'.*payload.*',
                        r'.*backdoor.*'
                    ]
                },
                'network_traces': {
                    'commands': self._get_network_commands(),
                    'patterns': [
                        r'.*:4444.*',
                        r'.*:5555.*',
                        r'.*:6666.*',
                        r'.*:8080.*',
                        r'.*ESTABLISHED.*'
                    ]
                },
                'system_traces': {
                    'commands': [
                        'ps aux',
                        'systemctl list-units',
                        'crontab -l',
                        'cat /etc/crontab'
                    ],
                    'patterns': [
                        r'.*exploit.*',
                        r'.*backdoor.*',
                        r'.*malware.*',
                        r'.*suspicious.*'
                    ]
                }
            }
    
    def _load_blue_team_checks(self):
        """加载蓝队检测检查项"""
        return {
            'forensic_commands': self._get_platform_commands('forensic_commands'),
            'memory_analysis': self._get_platform_commands('memory_analysis'),
            'timeline_analysis': self._get_platform_commands('timeline_analysis')
        }

    def verify_cleanup_effectiveness(self, cleanup_targets):
        """验证清理效果"""
        print("[*] 开始验证痕迹清理效果...")
        
        verification_results = {
            'log_verification': self._verify_log_cleanup(cleanup_targets.get('logs', [])),
            'process_verification': self._verify_process_cleanup(cleanup_targets.get('processes', [])),
            'file_verification': self._verify_file_cleanup(cleanup_targets.get('files', [])),
            'network_verification': self._verify_network_cleanup(cleanup_targets.get('network', [])),
            'system_verification': self._verify_system_cleanup(cleanup_targets.get('system', []))
        }
        
        # 汇总验证结果
        self.verification_report = self._generate_verification_report(verification_results)
        
        return self.verification_report
    
    def _verify_log_cleanup(self, log_targets):
        """验证日志清理"""
        print("[*] 验证日志清理...")
        
        found_traces = []
        
        for log_path in self.verification_rules['log_files']['paths']:
            if not os.path.exists(log_path):
                continue
            
            try:
                with open(log_path, 'r', encoding='utf-8', errors='ignore') as f:
                    content = f.read()
                    
                    for pattern in self.verification_rules['log_files']['patterns']:
                        matches = re.findall(pattern, content, re.IGNORECASE)
                        if matches:
                            for match in matches[:5]:  # 限制显示数量
                                found_traces.append({
                                    'type': 'log',
                                    'file': log_path,
                                    'pattern': pattern,
                                    'match': match,
                                    'severity': 'medium'
                                })
                                
            except Exception as e:
                print(f"[!] 读取日志文件失败 {log_path}: {e}")
        
        return found_traces
    
    def _verify_process_cleanup(self, process_targets):
        """验证进程清理"""
        print("[*] 验证进程清理...")
        
        found_traces = []
        
        # 检查/proc目录下的进程信息
        for proc_pattern in self.verification_rules['process_traces']['paths']:
            try:
                proc_files = glob.glob(proc_pattern)
                
                for proc_file in proc_files:
                    if not os.path.exists(proc_file):
                        continue
                    
                    try:
                        with open(proc_file, 'r', encoding='utf-8', errors='ignore') as f:
                            content = f.read()
                            
                            for pattern in self.verification_rules['process_traces']['patterns']:
                                if re.search(pattern, content, re.IGNORECASE):
                                    found_traces.append({
                                        'type': 'process',
                                        'file': proc_file,
                                        'pattern': pattern,
                                        'content': content[:100],  # 只显示前100字符
                                        'severity': 'high'
                                    })
                                    
                    except Exception:
                        continue  # 进程可能已经退出
                        
            except Exception as e:
                print(f"[!] 进程检查失败: {e}")
        
        return found_traces
    
    def _verify_file_cleanup(self, file_targets):
        """验证文件清理"""
        print("[*] 验证文件清理...")
        
        found_traces = []
        max_files_per_pattern = 100  # 限制每个模式检查的文件数量
        
        # 根据平台选择合适的文件路径
        if platform.system() == 'Windows':
            file_patterns = [
                'C:\\Windows\\Temp\\*.log',
                'C:\\Windows\\Temp\\*.tmp',
                'C:\\Temp\\*'
            ]
        else:
            file_patterns = self.verification_rules['file_traces']['paths']
        
        for file_pattern in file_patterns:
            try:
                files = glob.glob(file_pattern)
                
                # 限制文件数量以避免处理时间过长
                if len(files) > max_files_per_pattern:
                    files = files[:max_files_per_pattern]
                    print(f"[*] 限制检查文件数量为 {max_files_per_pattern} 个")
                
                for file_path in files:
                    if not os.path.exists(file_path) or os.path.isdir(file_path):
                        continue
                    
                    try:
                        # 检查文件名
                        filename = os.path.basename(file_path)
                        
                        # 根据平台选择合适的模式
                        if platform.system() == 'Windows':
                            patterns = ['backdoor', 'exploit', 'payload', 'shell', 'reverse']
                        else:
                            patterns = self.verification_rules['file_traces']['patterns']
                        
                        for pattern in patterns:
                            if re.search(pattern, filename, re.IGNORECASE):
                                found_traces.append({
                                    'type': 'file',
                                    'file': file_path,
                                    'pattern': pattern,
                                    'match_type': 'filename',
                                    'severity': 'medium'
                                })
                        
                        # 检查文件内容（小文件）
                        try:
                            file_size = os.path.getsize(file_path)
                            if file_size < 1024 * 100:  # 100KB以下
                                with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                                    content = f.read(1024)  # 只读取前1KB
                                    
                                    for pattern in patterns:
                                        if re.search(pattern, content, re.IGNORECASE):
                                            found_traces.append({
                                                'type': 'file',
                                                'file': file_path,
                                                'pattern': pattern,
                                                'match_type': 'content',
                                                'severity': 'high'
                                            })
                        except Exception:
                            continue
                                        
                    except Exception:
                        continue
                        
            except Exception as e:
                print(f"[!] 文件检查失败: {e}")
        
        return found_traces
    
    def _verify_network_cleanup(self, network_targets):
        """验证网络痕迹清理效果"""
        print("[*] 验证网络痕迹清理...")
        
        found_traces = []
        
        # 获取平台特定的网络验证命令
        network_commands = self._get_network_commands()
        
        for command in network_commands:
            try:
                # 检查是否为PowerShell命令
                if platform.system() == 'Windows' and command.startswith('powershell'):
                    # Windows PowerShell命令处理
                    try:
                        output = subprocess.check_output(
                            command,
                            shell=True,
                            universal_newlines=True,
                            stderr=subprocess.DEVNULL,
                            timeout=30
                        )
                    except Exception:
                        # 如果PowerShell命令失败，跳过
                        continue
                else:
                    # 其他平台的命令处理
                    if platform.system() == 'Windows':
                        # 在Windows上跳过非PowerShell的Linux命令
                        continue
                    
                    output = subprocess.check_output(
                        command,
                        shell=True,
                        universal_newlines=True,
                        stderr=subprocess.DEVNULL,
                        timeout=30
                    )
                
                # 分析输出中的可疑模式
                for pattern in self.verification_rules['network_traces']['patterns']:
                    matches = re.findall(pattern, output, re.IGNORECASE)
                    if matches:
                        found_traces.extend([{
                            'type': 'network',
                            'command': command,
                            'pattern': pattern,
                            'matches': matches[:5],  # 限制匹配数量
                            'severity': 'medium'
                        }])
                        
            except subprocess.TimeoutExpired:
                print(f"[!] 命令超时: {command}")
            except Exception as e:
                print(f"[!] 命令执行失败: {command} - {e}")
        
        return found_traces
    
    def _verify_system_cleanup(self, system_targets):
        """验证系统清理"""
        print("[*] 验证系统清理...")
        
        found_traces = []
        
        for command in self.verification_rules['system_traces']['commands']:
            try:
                if SECURITY_UTILS_AVAILABLE:
                    # 验证命令安全性
                    if not SecurityValidator.validate_command(command):
                        print(f"[!] 系统检查命令不安全: {command}")
                        continue
                    
                    # 安全执行命令
                    result = SecureCommandExecutor.execute_safe_command(
                        command,
                        timeout=15,
                        allowed_commands=['ps', 'netstat', 'ss', 'lsof', 'who', 'w', 'last', 'lastlog', 'history', 'find', 'grep', 'awk', 'sed']
                    )
                    
                    if result.get('returncode') == 0:
                        output = result.get('stdout', '')
                    else:
                        print(f"[!] 系统检查命令失败 {command}: {result.get('error', '')}")
                        continue
                else:
                    # 回退到原始方法
                    output = subprocess.check_output(
                        command,
                        shell=True,
                        universal_newlines=True,
                        stderr=subprocess.DEVNULL,
                        timeout=15
                    )
                
                for pattern in self.verification_rules['system_traces']['patterns']:
                    matches = re.findall(pattern, output, re.IGNORECASE)
                    if matches:
                        for match in matches[:3]:
                            found_traces.append({
                                'type': 'system',
                                'command': command,
                                'pattern': pattern,
                                'match': match,
                                'severity': 'medium'
                            })
                            
            except Exception as e:
                print(f"[!] 系统检查命令失败 {command}: {e}")
        
        return found_traces
    
    def _generate_verification_report(self, verification_results):
        """生成验证报告"""
        all_traces = []
        for category, traces in verification_results.items():
            all_traces.extend(traces)
        
        # 按严重程度分类
        severity_counts = defaultdict(int)
        for trace in all_traces:
            severity_counts[trace['severity']] += 1
        
        report = {
            'timestamp': time.time(),
            'total_traces_found': len(all_traces),
            'severity_breakdown': dict(severity_counts),
            'traces_by_category': {
                category: len(traces) 
                for category, traces in verification_results.items()
            },
            'detailed_traces': all_traces,
            'cleanup_effectiveness': self._calculate_cleanup_effectiveness(all_traces),
            'recommendations': self._generate_recommendations(all_traces)
        }
        
        return report
    
    def _calculate_cleanup_effectiveness(self, traces):
        """计算清理效果"""
        if not traces:
            return 100.0
        
        # 根据痕迹数量和严重程度计算效果
        high_severity = sum(1 for t in traces if t['severity'] == 'high')
        medium_severity = sum(1 for t in traces if t['severity'] == 'medium')
        low_severity = sum(1 for t in traces if t['severity'] == 'low')
        
        # 加权计算
        weighted_score = (high_severity * 3) + (medium_severity * 2) + (low_severity * 1)
        max_possible_score = len(traces) * 3
        
        effectiveness = max(0, 100 - (weighted_score / max_possible_score * 100))
        return round(effectiveness, 2)
    
    def _generate_recommendations(self, traces):
        """生成建议"""
        recommendations = []
        
        if not traces:
            recommendations.append("清理效果良好，未发现明显痕迹")
            return recommendations
        
        # 按类型分组建议
        trace_types = defaultdict(list)
        for trace in traces:
            trace_types[trace['type']].append(trace)
        
        for trace_type, type_traces in trace_types.items():
            if trace_type == 'log':
                recommendations.append(f"发现 {len(type_traces)} 个日志痕迹，建议进行更彻底的日志清理")
            elif trace_type == 'process':
                recommendations.append(f"发现 {len(type_traces)} 个进程痕迹，建议检查进程隐藏和清理")
            elif trace_type == 'file':
                recommendations.append(f"发现 {len(type_traces)} 个文件痕迹，建议进行安全删除")
            elif trace_type == 'network':
                recommendations.append(f"发现 {len(type_traces)} 个网络痕迹，建议清理网络连接")
            elif trace_type == 'system':
                recommendations.append(f"发现 {len(type_traces)} 个系统痕迹，建议清理系统配置")
        
        return recommendations
    
    def simulate_blue_team_detection(self):
        """模拟蓝队检测"""
        print("[*] 模拟蓝队检测流程...")
        
        detection_results = {
            'forensic_analysis': self._run_forensic_commands(),
            'memory_analysis': self._run_memory_analysis(),
            'timeline_analysis': self._run_timeline_analysis()
        }
        
        return detection_results
    
    def _run_forensic_commands(self):
        """运行取证命令"""
        print("[*] 执行取证分析...")
        
        results = []
        
        for command in self.blue_team_checks['forensic_commands']:
            try:
                # 检查是否为PowerShell命令
                if platform.system() == 'Windows' and command.startswith('powershell'):
                    # Windows PowerShell命令处理
                    try:
                        output = subprocess.check_output(
                            command,
                            shell=True,
                            universal_newlines=True,
                            stderr=subprocess.DEVNULL,
                            timeout=30
                        )
                    except Exception:
                        # 如果PowerShell命令失败，跳过
                        continue
                else:
                    # 其他平台的命令处理
                    if platform.system() == 'Windows':
                        # 在Windows上跳过非PowerShell的Linux命令
                        continue
                    
                    output = subprocess.check_output(
                        command,
                        shell=True,
                        universal_newlines=True,
                        stderr=subprocess.DEVNULL,
                        timeout=30
                    )
                
                if output.strip():
                    results.append({
                        'command': command,
                        'output': output[:500],  # 限制输出长度
                        'suspicious': self._analyze_command_output(output)
                    })
                    
            except Exception as e:
                results.append({
                    'command': command,
                    'error': str(e),
                    'suspicious': False
                })
        
        return results
    
    def _run_memory_analysis(self):
        """运行内存分析"""
        print("[*] 执行内存分析...")
        
        results = []
        
        for command in self.blue_team_checks['memory_analysis']:
            try:
                # 检查是否为PowerShell命令
                if platform.system() == 'Windows' and command.startswith('powershell'):
                    # Windows PowerShell命令处理
                    try:
                        output = subprocess.check_output(
                            command,
                            shell=True,
                            universal_newlines=True,
                            stderr=subprocess.DEVNULL,
                            timeout=20
                        )
                    except Exception:
                        # 如果PowerShell命令失败，跳过
                        continue
                else:
                    # 其他平台的命令处理
                    if platform.system() == 'Windows':
                        # 在Windows上跳过非PowerShell的Linux命令
                        continue
                    
                    output = subprocess.check_output(
                        command,
                        shell=True,
                        universal_newlines=True,
                        stderr=subprocess.DEVNULL,
                        timeout=20
                    )
                
                if output.strip():
                    results.append({
                        'command': command,
                        'output': output[:300],
                        'suspicious': self._analyze_command_output(output)
                    })
                    
            except Exception as e:
                results.append({
                    'command': command,
                    'error': str(e),
                    'suspicious': False
                })
        
        return results

    def _run_timeline_analysis(self):
        """运行时间线分析"""
        print("[*] 执行时间线分析...")
        
        results = []
        
        for command in self.blue_team_checks['timeline_analysis']:
            try:
                # 检查是否为PowerShell命令
                if platform.system() == 'Windows' and command.startswith('powershell'):
                    # Windows PowerShell命令处理
                    try:
                        output = subprocess.check_output(
                            command,
                            shell=True,
                            universal_newlines=True,
                            stderr=subprocess.DEVNULL,
                            timeout=25
                        )
                    except Exception:
                        # 如果PowerShell命令失败，跳过
                        continue
                else:
                    # 其他平台的命令处理
                    if platform.system() == 'Windows':
                        # 在Windows上跳过非PowerShell的Linux命令
                        continue
                    
                    output = subprocess.check_output(
                        command,
                        shell=True,
                        universal_newlines=True,
                        stderr=subprocess.DEVNULL,
                        timeout=25
                    )
                
                if output.strip():
                    results.append({
                        'command': command,
                        'output': output[:400],
                        'suspicious': self._analyze_command_output(output)
                    })
                    
            except Exception as e:
                results.append({
                    'command': command,
                    'error': str(e),
                    'suspicious': False
                })
        
        return results
    
    def _analyze_command_output(self, output):
        """分析命令输出是否可疑"""
        suspicious_indicators = [
            'exploit', 'payload', 'shell', 'backdoor', 'malware',
            'suspicious', 'privilege', 'escalation', 'rootkit'
        ]
        
        output_lower = output.lower()
        for indicator in suspicious_indicators:
            if indicator in output_lower:
                return True
        
        return False


class CleanupValidator(object):
    """清理验证器"""
    
    def __init__(self):
        self.validation_rules = self._load_validation_rules()
        self.cleanup_history = []
    
    def _load_validation_rules(self):
        """加载验证规则"""
        return {
            'critical_files': [
                '/var/log/auth.log',
                '/var/log/secure',
                '/var/log/audit/audit.log',
                '/home/*/.bash_history',
                '/root/.bash_history'
            ],
            'critical_processes': [
                'sshd', 'systemd', 'kernel'
            ],
            'protected_directories': [
                '/etc', '/usr/bin', '/usr/sbin', '/bin', '/sbin'
            ],
            'validation_checks': {
                'file_integrity': True,
                'process_validation': True,
                'system_stability': True,
                'log_consistency': True
            }
        }
    
    def validate_cleanup_safety(self, cleanup_plan):
        """验证清理安全性"""
        print("[*] 验证清理操作安全性...")
        
        validation_results = {
            'safe_to_proceed': True,
            'warnings': [],
            'critical_issues': [],
            'recommendations': []
        }
        
        # 检查关键文件
        for target in cleanup_plan.get('files', []):
            if self._is_critical_file(target):
                validation_results['warnings'].append(f"目标包含关键文件: {target}")
        
        # 检查关键进程
        for target in cleanup_plan.get('processes', []):
            if self._is_critical_process(target):
                validation_results['critical_issues'].append(f"目标包含关键进程: {target}")
                validation_results['safe_to_proceed'] = False
        
        # 检查受保护目录
        for target in cleanup_plan.get('directories', []):
            if self._is_protected_directory(target):
                validation_results['critical_issues'].append(f"目标包含受保护目录: {target}")
                validation_results['safe_to_proceed'] = False
        
        return validation_results
    
    def _is_critical_file(self, file_path):
        """检查是否为关键文件"""
        for critical_pattern in self.validation_rules['critical_files']:
            if critical_pattern in file_path:
                return True
        return False
    
    def _is_critical_process(self, process_name):
        """检查是否为关键进程"""
        return process_name in self.validation_rules['critical_processes']
    
    def _is_protected_directory(self, dir_path):
        """检查是否为受保护目录"""
        for protected_dir in self.validation_rules['protected_directories']:
            if dir_path.startswith(protected_dir):
                return True
        return False
    
    def post_cleanup_validation(self, cleanup_results):
        """清理后验证"""
        print("[*] 执行清理后验证...")
        
        validation_results = {
            'system_stable': self._check_system_stability(),
            'critical_services': self._check_critical_services(),
            'file_integrity': self._check_file_integrity(),
            'cleanup_success': self._analyze_cleanup_results(cleanup_results)
        }
        
        return validation_results
    
    def _check_system_stability(self):
        """检查系统稳定性"""
        try:
            # 检查系统负载
            with open('/proc/loadavg', 'r') as f:
                load = f.read().strip().split()[0]
                if float(load) > 10.0:
                    return {'stable': False, 'reason': 'High system load'}
            
            # 检查内存使用
            with open('/proc/meminfo', 'r') as f:
                meminfo = f.read()
                mem_total = int(re.search(r'MemTotal:\s+(\d+)', meminfo).group(1))
                mem_free = int(re.search(r'MemFree:\s+(\d+)', meminfo).group(1))
                
                if (mem_free / mem_total) < 0.1:  # 可用内存少于10%
                    return {'stable': False, 'reason': 'Low memory'}
            
            return {'stable': True, 'reason': 'System appears stable'}
            
        except Exception as e:
            return {'stable': False, 'reason': f'Check failed: {e}'}
    
    def _check_critical_services(self):
        """检查关键服务"""
        critical_services = ['sshd', 'systemd', 'NetworkManager']
        service_status = {}
        
        for service in critical_services:
            try:
                output = subprocess.check_output(
                    ['systemctl', 'is-active', service],
                    universal_newlines=True,
                    stderr=subprocess.DEVNULL
                )
                service_status[service] = output.strip() == 'active'
            except Exception:
                service_status[service] = False
        
        return service_status
    
    def _check_file_integrity(self):
        """检查文件完整性"""
        integrity_results = {}
        
        # 检查关键系统文件
        critical_files = ['/etc/passwd', '/etc/shadow', '/etc/sudoers']
        
        for file_path in critical_files:
            if os.path.exists(file_path):
                try:
                    with open(file_path, 'rb') as f:
                        content = f.read()
                        file_hash = hashlib.sha256(content).hexdigest()
                        integrity_results[file_path] = {
                            'exists': True,
                            'hash': file_hash,
                            'size': len(content)
                        }
                except Exception as e:
                    integrity_results[file_path] = {
                        'exists': True,
                        'error': str(e)
                    }
            else:
                integrity_results[file_path] = {'exists': False}
        
        return integrity_results
    
    def _analyze_cleanup_results(self, cleanup_results):
        """分析清理结果"""
        analysis = {
            'total_operations': 0,
            'successful_operations': 0,
            'failed_operations': 0,
            'success_rate': 0.0
        }
        
        for category, operations in cleanup_results.items():
            for operation in operations:
                analysis['total_operations'] += 1
                if operation.get('success', False):
                    analysis['successful_operations'] += 1
                else:
                    analysis['failed_operations'] += 1
        
        if analysis['total_operations'] > 0:
            analysis['success_rate'] = (
                analysis['successful_operations'] / analysis['total_operations'] * 100
            )
        
        return analysis


class TraceCleanupManager(object):
    """痕迹清理管理器"""
    
    def __init__(self):
        self.verifier = TraceVerifier()
        self.validator = CleanupValidator()
        self.cleanup_cycles = 0
        self.max_cleanup_cycles = 3
        self.cleanup_history = []
    
    def execute_verified_cleanup(self, cleanup_targets):
        """执行验证式清理"""
        print("[*] 开始验证式痕迹清理流程...")
        
        cleanup_session = {
            'session_id': hashlib.md5(str(time.time()).encode()).hexdigest()[:8],
            'start_time': time.time(),
            'cycles': []
        }
        
        while self.cleanup_cycles < self.max_cleanup_cycles:
            self.cleanup_cycles += 1
            print(f"\n[*] 执行第 {self.cleanup_cycles} 轮清理...")
            
            cycle_result = self._execute_cleanup_cycle(cleanup_targets)
            cleanup_session['cycles'].append(cycle_result)
            
            # 检查是否需要继续清理
            if cycle_result['verification_report']['total_traces_found'] == 0:
                print("[+] 清理完成，未发现残留痕迹")
                break
            elif cycle_result['verification_report']['cleanup_effectiveness'] > 95:
                print("[+] 清理效果良好，停止进一步清理")
                break
            elif self.cleanup_cycles >= self.max_cleanup_cycles:
                print("[!] 达到最大清理轮数，停止清理")
                break
            else:
                print(f"[*] 发现残留痕迹，准备第 {self.cleanup_cycles + 1} 轮清理...")
                time.sleep(2)  # 短暂等待
        
        cleanup_session['end_time'] = time.time()
        cleanup_session['total_cycles'] = self.cleanup_cycles
        
        # 生成最终报告
        final_report = self._generate_final_report(cleanup_session)
        
        # 保存清理历史
        self.cleanup_history.append(cleanup_session)
        
        return final_report
    
    def _execute_cleanup_cycle(self, cleanup_targets):
        """执行单轮清理"""
        cycle_result = {
            'cycle_number': self.cleanup_cycles,
            'timestamp': time.time(),
            'pre_validation': None,
            'cleanup_results': None,
            'verification_report': None,
            'post_validation': None,
            'recommendations': []
        }
        
        try:
            # 1. 清理前验证
            print("[*] 清理前安全验证...")
            cycle_result['pre_validation'] = self.validator.validate_cleanup_safety(cleanup_targets)
            
            if not cycle_result['pre_validation']['safe_to_proceed']:
                print("[!] 安全验证失败，跳过清理")
                cycle_result['recommendations'].append("安全验证失败，建议检查清理目标")
                return cycle_result
            
            # 2. 执行清理操作
            print("[*] 执行清理操作...")
            cycle_result['cleanup_results'] = self._perform_cleanup(cleanup_targets)
            
            # 3. 验证清理效果
            print("[*] 验证清理效果...")
            cycle_result['verification_report'] = self.verifier.verify_cleanup_effectiveness(cleanup_targets)
            
            # 4. 清理后验证
            print("[*] 清理后系统验证...")
            cycle_result['post_validation'] = self.validator.post_cleanup_validation(
                cycle_result['cleanup_results']
            )
            
            # 5. 生成建议
            cycle_result['recommendations'] = self._generate_cycle_recommendations(cycle_result)
            
        except Exception as e:
            print(f"[!] 清理周期执行失败: {e}")
            cycle_result['error'] = str(e)
        
        return cycle_result
    
    def _perform_cleanup(self, cleanup_targets):
        """执行实际清理操作"""
        # 这里是清理操作的占位符
        # 实际实现需要根据具体的清理需求来编写
        
        cleanup_results = {
            'logs': [],
            'processes': [],
            'files': [],
            'network': [],
            'system': []
        }
        
        # 模拟清理操作
        for category, targets in cleanup_targets.items():
            for target in targets:
                try:
                    # 这里应该是实际的清理逻辑
                    print(f"[*] 清理 {category}: {target}")
                    
                    cleanup_results[category].append({
                        'target': target,
                        'success': True,
                        'method': 'simulated_cleanup'
                    })
                    
                except Exception as e:
                    cleanup_results[category].append({
                        'target': target,
                        'success': False,
                        'error': str(e)
                    })
        
        return cleanup_results
    
    def _generate_cycle_recommendations(self, cycle_result):
        """生成周期建议"""
        recommendations = []
        
        if cycle_result.get('verification_report'):
            effectiveness = cycle_result['verification_report']['cleanup_effectiveness']
            
            if effectiveness < 50:
                recommendations.append("清理效果较差，建议检查清理方法")
            elif effectiveness < 80:
                recommendations.append("清理效果一般，建议进行二次清理")
            else:
                recommendations.append("清理效果良好")
            
            # 添加验证报告中的建议
            recommendations.extend(
                cycle_result['verification_report'].get('recommendations', [])
            )
        
        return recommendations
    
    def _generate_final_report(self, cleanup_session):
        """生成最终报告"""
        final_report = {
            'session_summary': {
                'session_id': cleanup_session['session_id'],
                'duration': cleanup_session['end_time'] - cleanup_session['start_time'],
                'total_cycles': cleanup_session['total_cycles'],
                'success': True
            },
            'effectiveness_trend': [],
            'final_effectiveness': 0.0,
            'remaining_traces': 0,
            'overall_recommendations': [],
            'detailed_cycles': cleanup_session['cycles']
        }
        
        # 计算效果趋势
        for cycle in cleanup_session['cycles']:
            if cycle.get('verification_report'):
                effectiveness = cycle['verification_report']['cleanup_effectiveness']
                final_report['effectiveness_trend'].append(effectiveness)
        
        if final_report['effectiveness_trend']:
            final_report['final_effectiveness'] = final_report['effectiveness_trend'][-1]
        
        # 计算剩余痕迹
        last_cycle = cleanup_session['cycles'][-1] if cleanup_session['cycles'] else {}
        if last_cycle.get('verification_report'):
            final_report['remaining_traces'] = last_cycle['verification_report']['total_traces_found']
        
        # 生成总体建议
        final_report['overall_recommendations'] = self._generate_overall_recommendations(
            final_report
        )
        
        return final_report
    
    def _generate_overall_recommendations(self, final_report):
        """生成总体建议"""
        recommendations = []
        
        effectiveness = final_report['final_effectiveness']
        remaining_traces = final_report['remaining_traces']
        
        if effectiveness >= 95 and remaining_traces == 0:
            recommendations.append("清理完成，系统痕迹已基本清除")
        elif effectiveness >= 80:
            recommendations.append("清理效果良好，建议定期检查")
        elif effectiveness >= 60:
            recommendations.append("清理效果一般，建议改进清理策略")
        else:
            recommendations.append("清理效果较差，建议重新评估清理方法")
        
        if remaining_traces > 0:
            recommendations.append(f"仍有 {remaining_traces} 个痕迹残留，建议手动处理")
        
        return recommendations
    
    def interactive_cleanup_menu(self):
        """交互式清理菜单"""
        while True:
            print("\n" + "="*50)
            print("痕迹清理验证系统")
            print("="*50)
            print("1. 执行完整清理验证流程")
            print("2. 仅验证现有痕迹")
            print("3. 模拟蓝队检测")
            print("4. 查看清理历史")
            print("5. 生成清理报告")
            print("0. 退出")
            print("="*50)
            
            try:
                choice = input("请选择操作: ").strip()
                
                if choice == '1':
                    self._interactive_full_cleanup()
                elif choice == '2':
                    self._interactive_trace_verification()
                elif choice == '3':
                    self._interactive_blue_team_simulation()
                elif choice == '4':
                    self._show_cleanup_history()
                elif choice == '5':
                    self._generate_cleanup_report()
                elif choice == '0':
                    break
                else:
                    print("[!] 无效选择")
                    
            except KeyboardInterrupt:
                print("\n[*] 操作中断")
                break
            except Exception as e:
                print(f"[!] 操作失败: {e}")
    
    def _interactive_full_cleanup(self):
        """交互式完整清理"""
        print("\n配置清理目标:")
        
        cleanup_targets = {
            'logs': [],
            'processes': [],
            'files': [],
            'network': [],
            'system': []
        }
        
        # 简化的目标配置
        log_targets = input("日志清理目标 (逗号分隔): ").strip()
        if log_targets:
            cleanup_targets['logs'] = [t.strip() for t in log_targets.split(',')]
        
        file_targets = input("文件清理目标 (逗号分隔): ").strip()
        if file_targets:
            cleanup_targets['files'] = [t.strip() for t in file_targets.split(',')]
        
        print("\n[*] 开始执行清理...")
        result = self.execute_verified_cleanup(cleanup_targets)
        
        print("\n" + "="*40)
        print("清理结果摘要")
        print("="*40)
        print(f"会话ID: {result['session_summary']['session_id']}")
        print(f"清理轮数: {result['session_summary']['total_cycles']}")
        print(f"最终效果: {result['final_effectiveness']:.2f}%")
        print(f"剩余痕迹: {result['remaining_traces']}")
        print("="*40)
    
    def _interactive_trace_verification(self):
        """交互式痕迹验证"""
        print("\n[*] 执行痕迹验证...")
        
        # 使用空的清理目标进行验证
        result = self.verifier.verify_cleanup_effectiveness({})
        
        print(f"\n发现痕迹: {result['total_traces_found']}")
        print(f"清理效果: {result['cleanup_effectiveness']:.2f}%")
        
        if result['detailed_traces']:
            print("\n详细痕迹:")
            for trace in result['detailed_traces'][:10]:  # 只显示前10个
                print(f"  - {trace['type']}: {trace.get('file', trace.get('command', 'N/A'))}")
    
    def _interactive_blue_team_simulation(self):
        """交互式蓝队模拟"""
        print("\n[*] 模拟蓝队检测...")
        
        result = self.verifier.simulate_blue_team_detection()
        
        print("\n蓝队检测结果:")
        for category, analyses in result.items():
            suspicious_count = sum(1 for a in analyses if a.get('suspicious', False))
            print(f"  {category}: {suspicious_count}/{len(analyses)} 可疑")
    
    def _show_cleanup_history(self):
        """显示清理历史"""
        if not self.cleanup_history:
            print("\n[*] 暂无清理历史")
            return
        
        print(f"\n清理历史 ({len(self.cleanup_history)} 个会话):")
        for i, session in enumerate(self.cleanup_history[-5:], 1):  # 只显示最近5个
            duration = session['end_time'] - session['start_time']
            print(f"  {i}. 会话 {session['session_id']}: {session['total_cycles']} 轮, {duration:.1f}秒")
    
    def _generate_cleanup_report(self):
        """生成清理报告"""
        if not self.cleanup_history:
            print("\n[*] 暂无清理历史，无法生成报告")
            return
        
        report_path = f"/tmp/cleanup_report_{int(time.time())}.json"
        
        try:
            with open(report_path, 'w') as f:
                json.dump(self.cleanup_history, f, indent=2)
            
            print(f"\n[+] 清理报告已生成: {report_path}")
            
        except Exception as e:
            print(f"[!] 报告生成失败: {e}")


def main():
    """主函数 - 用于测试"""
    print("痕迹清理闭环验证系统")
    print("="*30)
    
    try:
        # 创建管理器
        manager = TraceCleanupManager()
        
        # 启动交互式菜单
        manager.interactive_cleanup_menu()
        
    except KeyboardInterrupt:
        print("\n[*] 程序中断")
    except Exception as e:
        print(f"[!] 程序异常: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()